package net.towee.client.managers.impl;

import java.util.Collections;
import java.util.Map;

import net.towee.client.managers.AttachmentsManager;
import net.towee.model.repo.AttachmentIdentity;
import net.towee.model.repo.AttachmentInfo;
import net.towee.server.rpc.services.ToweeServiceAsync;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class AttachmentsManagerImpl implements AttachmentsManager {
	private final Map<String, AttachmentInfo> attachments = Collections.emptyMap();
	private final ToweeServiceAsync service;

	@Inject
	public AttachmentsManagerImpl(ToweeServiceAsync service) {
		this.service = service;
	}
	
	@Override
	public void getAttachmentInfo(final String attachmentId, final AsyncCallback<AttachmentInfo> handler) {
		if(attachments.containsKey(attachmentId))
			handler.onSuccess( attachments.get(attachmentId) );
		else
			service.getAttachmentInfo(attachmentId, new AsyncCallback<AttachmentInfo>(){
				@Override
				public void onFailure(Throwable caught) {}

				@Override
				public void onSuccess(AttachmentInfo result) {
					attachments.put(attachmentId, result);
					handler.onSuccess(result);
				}
			});
	}

	@Override
	public void createAttachmentIdentity(String rawAttachmentId, AsyncCallback<AttachmentIdentity> handler) {
		service.createAttachmentIdentity(rawAttachmentId, handler);
	}
}
